package pers.llc.css.countDownLatch;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @author fancy
 * @time 2018-09-30
 */
public class MyCountDownLatch2 {

    public static long timeTask(int nThreads, final Runnable task) throws InterruptedException {

        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(nThreads);

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 4, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        for (int i = 0; i < nThreads; i++) {
            threadPool.execute(() -> {
                try {
                    try {
                        startGate.await();
                    } finally {
                        endGate.countDown();
                    }
                    task.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        long start = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();
        System.out.println(end - start);
        return end - start;

    }

    public static void main(String[] args) {
        try {
            MyCountDownLatch2.timeTask(4, ()-> System.out.println("execute thread ing"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

